<?php
namespace app\shop\library;

use cubox\Cubox;

class Lock{
    const LOCK_KEY = 'shop-lock';


    public static $isLocked = false;
    /**
     * 获取锁
     */
    public static function acquire(){
        $cache =  Cubox::app('shop')->cache();
        $time = 100;
        while ($time>0){
            if ($cache->setnx(self::LOCK_KEY,1)){
                $cache->expire(self::LOCK_KEY,10);
                self::$isLocked = true;
                return true;
            }else{
                // 休眠100毫秒
                usleep(10*1000);
                $time --;
            }
        }

        throw new \Exception('获取锁失败');
    }

    /**
     * 释放锁
     */
    public static function release(){
        $cache =  Cubox::app('shop')->cache();
        $cache->del(self::LOCK_KEY);
        self::$isLocked = false;
    }
}